<template>
	<view>
		<view class="my-infoset">
			<view class="card">
				<text>昵称：</text>
				<input type="text" class="weui-input" placeholder="请输入昵称" v-model="userinfo.nickName" />
				<text class="error" v-if="nickNameError" style="color: red;font-size: 12px;">{{ nickNameError }}</text>
			</view>
			<view class="card">
				<text>年龄：</text>
				<input type="number" class="weui-input" placeholder="请输入年龄" v-model="userinfo.age" />
			</view>
			<view class="card">
				<text>手机号：</text>
				<input type="text" class="weui-input" placeholder="请输入手机号" v-model="userinfo.phoneNumber" />
			</view>
			<view class="card">
				<text>邮箱：</text>
				<input type="email" class="weui-input" placeholder="请输入邮箱" v-model="userinfo.email" />
			</view>
		</view>
		<button type="primary" @click="save()">保存</button>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';

	export default {
		computed: {
			...mapState('m_user', ['userinfo', 'userId']),
		},
		data() {
			return {
				nickNameError: '' // 用于存储昵称错误消息
			};
		},
		onLoad() {
			this.fetchUserInfo();
		},
		methods: {
			async fetchUserInfo() {
				if (!this.userId) {
					console.error('UserId 未定义，无法加载用户信息');
					return;
				}
				try {
					const res = await uni.$http.get(`/wx/userlist/${this.userId}`);
					//返回的数据可以直接合并到 userinfo 中
					this.$set(this.$store.state.m_user, 'userinfo', {
						...this.userinfo,
						...res.data.data
					});
					console.log(res);
				} catch (error) {
					console.error('查询用户信息时发生错误:', error);
				}
			},
			async save() {
				if (!this.userinfo.nickName) {
					this.nickNameError = '昵称不能为空';
					return;
				}
				this.nickNameError = ''; // 清除错误消息

				try {
					const res = await uni.$http.put('/wx/updataUserinfo', this.userinfo); 
					console.log(res);
					uni.showToast({
					    title: '保存成功！',
					    icon: 'none'
					});
				} catch (error) {
					console.error('保存用户信息时发生错误:', error);
				}
			}
		}
	}
</script>
<style lang="scss">
	.my-infoset .card {
		background-color: #fff;
		margin: 5px;
		height: 50px;
		display: flex;
		align-items: center; // 垂直居中
	}
</style>